package com.zjy.common.utils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

/**
 * @author zhangjianyu
 * email: 578547270@qq.com
 * create_time: 2024-07-21 21:47
 * description:
 */
public class VirtualThreadUtils {

    private static ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();

    /**
     * 异步执行方法
     *
     * @param task 任务逻辑
     */
    public static CompletableFuture<Void> runAsync(Runnable task) {
        return CompletableFuture.runAsync(task, executorService);
    }

    /**
     * 创建带返回值的异步任务
     *
     * @param supplier 业务方法
     * @param <T>      返回值的类型
     * @return 异步结果
     */
    public static <T> CompletableFuture<T> supplyAsync(Supplier<T> supplier) {
        return CompletableFuture.supplyAsync(supplier, executorService);
    }

    /**
     * 全部完成
     *
     * @param futures
     */
    public static void allOf(List<CompletableFuture> futures) {
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
    }

    /**
     * 全部完成
     *
     * @param futures
     */
    public static <T> void allOfType(List<CompletableFuture<T>> futures) {
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
    }


}
